package com.jbp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.model.Level;
import com.jbp.model.UserNobility;
import com.jbp.model.UserRelation;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.*;
import com.jbp.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.jbp.model.User;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 
 *
 * @author lucheng feng
 * @email jbp@gmail.com
 * @date 2020-06-13 23:01:27
 */
@Api(tags ="APP接口--用户相关接口" )
@RestController
@ApiIgnore
@RequestMapping("/rest/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisConfigService redisConfigService;

    @Autowired
    private VisitorLogService visitorLogService;

    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private PropertyService propertyService;
    @Autowired
    private TecentMsgService tecentMsgService;
    @Autowired
    private UserNobilityService userNobilityService;
    @Autowired
    private UserLevelService userLevelService;
    @Autowired
    private UserCreatorService userCreatorService;

    @ApiOperation(value="修改用户信息",notes="修改用户信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "手机号",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "姓名",paramType = "query"),
            @ApiImplicitParam(name = "sex",value = "性别 man 男 women 女",paramType = "query"),
            @ApiImplicitParam(name = "city",value = "城市",paramType = "query"),
            @ApiImplicitParam(name = "brithday",value = "生日",paramType = "query"),
            @ApiImplicitParam(name = "height",value = "身高",paramType = "query"),
            @ApiImplicitParam(name = "img",value = "头像",paramType = "query"),
            @ApiImplicitParam(name = "individuality",value = "个性签名",paramType = "query"),
            @ApiImplicitParam(name = "interest",value = "兴趣爱好",paramType = "query"),
            @ApiImplicitParam(name = "isOnline",value = " 在线 online  离线 offline 隐身 hiding",paramType = "query"),
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name = "vocation",value = "职业",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name = "password",value = "密码",paramType = "query")
    })
    @PostMapping("/updateUser")
    public R updateUser(@RequestAttribute("userId") Integer userId,@RequestBody User user){
        user.setId(userId);
        user = userService.modifyInformation(user);
        return R.ok().put("data",user);
    }


    @ApiOperation(value="获取用户信息",notes="获取用户信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = User.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query")
    })
    @GetMapping("/info")
    public R info(@RequestParam(value = "isMain", required = false)Integer isMain, @RequestAttribute("userId")Integer userId, @RequestParam(value = "otherId", required = false)Integer otherId){
        ///如果传了otherId 就根据otherid查用户
        if (otherId!=null) {
            if (isMain!=null && isMain==1 && !userId.equals(otherId)) {
                //添加访客记录
                visitorLogService.addLog(userId, otherId);
            }

            //取缓存  不是自己  不是主页才取
            if (isMain!=null && isMain==0 && !userId.equals(otherId)) {
                User cache = (User) redisConfigService.getJson("user:cache:" + otherId, User.class);

                if (cache != null) {
                    return R.ok().put("data", cache);
                }
            }

            User user = userService.getById(otherId);
            if (user==null) {
                return R.error("用户不存在");
            }
            user = userService.getUserInformation(userId, user);
            //粉丝
            int fs = userRelationService.count(new QueryWrapper<UserRelation>().eq("user_id", otherId).in("status", 1, 3));
            user.setFansNo(fs);

            //设缓存
            redisConfigService.setJson("user:cache:"+user.getId(), user, 60*1);
            return R.ok().put("data",user);
        } else {
            User user = userService.getById(userId);
            user = userService.getUserInformation(userId, user);
            //粉丝
            int fs = userRelationService.count(new QueryWrapper<UserRelation>().eq("user_id", userId).in("status", 1, 3));
            user.setFansNo(fs);
            return R.ok().put("data",user);
        }

    }

    @ApiOperation(value="设置密码",notes="设置密码")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name = "messageCode",value = "验证码",paramType = "query"),
            @ApiImplicitParam(name = "password",value = "密码",paramType = "query")
    })
    @PostMapping("/updatePwd")
    public R updatePwd(@RequestBody User user,@RequestAttribute("userId")Integer userId){
        if (StringUtils.isEmpty(user.getMessageCode())){
            return R.error("验证码为空");
        }
        if (StringUtils.isEmpty(user.getPassword())){
            return R.error("密码为空");
        }
        if (!RegularExpressionUtil.checkPassword(user.getPassword())){
            return R.error("密码规则 8~16位 数字、字母组合");
        }
        User us = userService.getById(userId);
        Object obj= redisConfigService.get(Constant.CODE_PREFIX+us.getMobile());
        if (obj == null){
            return R.error("请先发送验证码");
        }
        if (!obj.equals(user.getMessageCode())){
            return R.error("验证码不正确");
        }
        /**
         * 清除验证码缓存
         */
        us.setPassword(StrToMillsUtil.passwordEncode(user.getPassword(),us.getSalt()));
        userService.updateById(us);
        redisConfigService.remove(Constant.CODE_PREFIX+user.getMobile());
        return R.ok();
    }

    @ApiOperation(value="获取用户等级信息",notes="获取用户等级信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Level.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @GetMapping("/getLevel")
    public R getLevel(@RequestAttribute("userId") Integer userId){
        Level level = new Level();
        int experience = userLevelService.getExperience(userId);
        level.setLevel(LevelUtil.getLevel(experience));
        level.setLevelOn(userLevelService.levelOn(userId));

        //当前等级经验值
        int experThisLevel = LevelUtil.getExperByLevel(level.getLevel());
        //下一等级经验值
        int experNextLevel = LevelUtil.getExperByLevel(level.getLevel()+1);
        level.setLevelValue(experNextLevel - experThisLevel);
        level.setSubLevel(experNextLevel-experience);

        return R.ok(level);
    }

    /**获取爵位信息*/
    @GetMapping("/getNobility")
    public R getNobility(@RequestAttribute("userId") Integer userId){
        UserNobility userNobility = userNobilityService.getUserNobility(userId);
        return R.ok(userNobility);
    }

    ///用户搜索
    @ApiOperation(value="新用户列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = User.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @GetMapping("/latestUser")
    public R latestUser(@RequestParam Map<String, Object> params, @RequestAttribute("userId") Integer userId){
        params.put("userId",userId);
        PageUtils page = userService.latestUser(params);

        return R.ok(page);
    }

    ///用户搜索
    @ApiOperation(value="推荐用户列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = User.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @GetMapping("/recommendUser")
    public R recommendUser(@RequestParam Map<String, Object> params, @RequestAttribute("userId") Integer userId){
        params.put("userId",userId);
        PageUtils page = userService.recommendUser(params);

        return R.ok(page);
    }
    @GetMapping("/guessYouLike")
    public R guessYouLike(@RequestParam Map<String, Object> params, @RequestAttribute("userId") Integer userId){
        params.put("userId",userId);
        PageUtils page = userService.youLikeUser(params);

        return R.ok(page);
    }

    @GetMapping("/updateTencent")
    public R updateTencent( @RequestAttribute("userId") Integer userId){
        tecentMsgService.addUser(userId);

        return R.ok();
    }

    @GetMapping("/isCreator")
    public R isCreator( @RequestAttribute("userId") Integer userId){
        return R.ok(userCreatorService.isCreator(userId));
    }

    @GetMapping("/creatXiaohao")
    public R creatXiaohao( @RequestAttribute("userId") Integer userId){
        return R.ok("success", userCreatorService.createXiaoHao(userId));
    }
}
